/**
 * sensor.c
 */

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include <Base.h>

#include "../alarmCommon.h"
#include "alarmSensor.h"

Sensor *findSensor(Sensor *pList, char addr) {
	Sensor *pSensor = pList;
	while (pSensor != NULL) {
		if (pSensor->conf.addr == addr) {
			break;
		}
		pSensor = pSensor->pNext;
	}

	return pSensor;
}

Sensor *allocSensor(char *pBuff, char *pCmd) {
    *pCmd = SENSOR_CMD_ADD;
	Sensor *pSensor = (Sensor *) calloc(1, sizeof(Sensor));
	if (pSensor == NULL) {
		LOGERROR("pSensor == NULL\n");
		return NULL;
	}

	int confSize = sizeof(SensorConf);
	char *pConfBuff = pBuff;
	memcpy(&pSensor->conf, pConfBuff, confSize);	// SensorConf is ONE byte align
	pSensor->pSchemeList = allocSchemeList(pConfBuff + confSize);	// maybe no sche

	return pSensor;
}

void processSensorCmd(Sensor **ppList, Sensor *pProcSensor, char cmd) {
	Sensor *pSensor = *ppList;
	Sensor *pNextSensor;
	if (pSensor == NULL && cmd == SENSOR_CMD_ADD) {
		*ppList = pProcSensor;
		return;
	}

	while (pSensor != NULL) {
		pNextSensor = pSensor->pNext;

		// find in head
 		if (pSensor == *ppList && pSensor->conf.addr == pProcSensor->conf.addr) {
			if (cmd == SENSOR_CMD_DEL) {
				freeSensor(pSensor);
				*ppList = pNextSensor;
			} else if (cmd == SENSOR_CMD_ADD || cmd == SENSOR_CMD_MOD) {
				freeSensor(pSensor);
				pProcSensor->pNext = pNextSensor;
				*ppList = pProcSensor;
			} else {
				LOGERROR("unknown sensor command = %d\n", cmd);
			}
			break;
		}
		// find not in head
		if (pNextSensor != NULL && pNextSensor->conf.addr == pProcSensor->conf.addr) {
			if (cmd == SENSOR_CMD_DEL) {
				pSensor->pNext = pNextSensor->pNext;
				freeSensor(pNextSensor);
			} else if (cmd == SENSOR_CMD_ADD || cmd == SENSOR_CMD_MOD) {
				pSensor->pNext = pProcSensor;
				pProcSensor->pNext = pNextSensor->pNext;
				freeSensor(pNextSensor);
			} else {
				LOGERROR("unknown sensor command = %d\n", cmd);
			}
			break;
		}
		// not find
		if(pNextSensor == NULL && cmd == SENSOR_CMD_ADD) {
			pSensor->pNext = pProcSensor;
			pProcSensor->pNext = NULL;
			break;
		}

		pSensor = pNextSensor;
	}
}

int sensorToBuff(char *pBuff, int buffSize, Sensor *pSensor) {
	int confSize = sizeof(SensorConf);
	int needSize = confSize + getSchemeListBuffSize(pSensor->pSchemeList);
	printf("sensor need buffer size = %d,confSize= %d,scheme = %d\n", needSize,confSize,getSchemeListBuffSize(pSensor->pSchemeList));

	if (needSize > buffSize) {
		LOGERROR("needSize > buffSize\n");
		return -1;
	}

	//pBuff[0] = SENSOR_CMD_ADD;
	//pBuff[1] = 1;
	char *pConfBuff = pBuff;
	memcpy(pConfBuff, &pSensor->conf, confSize);
	schemeListToBuff(pConfBuff + confSize, needSize - confSize, pSensor->pSchemeList);

	return needSize;
}

